/*
2019-05-10 手动造轮子，实现es的symbol类型
*/

(function(){
  let root = this;
  let symbol_formap={};
  
  let generatename=(function(){
    let prefix=0;
    return function(desp){
      prefix++;
      return '@@'+desp+"_"+prefix;
    }
  })();

  let SymbolPolyfill=function(descript){
    // 使用new SymbolPolyfill()，报错
    if(this instanceof SymbolPolyfill) {
      //debugger;
      throw new TypeError('SymbolPolyfill为非构造函数，不能使用new');
    }

    let description=descript===undefined?undefined:String(descript)
    let symbol=Object.create({
      toString: function(){
        return this.__Name__;
      }
    });

    Object.defineProperties(symbol, {
      '__Name__': {
        value: generatename(description),
        writable: false,
        enumerable: false,
        configurable: false
      }
    })


    // 本质上是一个全局的symbol对象，desp相同时，返回的内容相同
    // SymbolPolyfill.for([[desp]]);
    Object.defineProperties(SymbolPolyfill, {
      'for': {
        value: function(desp){
          let descString = desp === undefined ? 'undefined' : String(desp);
          return symbol_formap[descString]?forMap[descString] : forMap[descString] = SymbolPolyfill(descString);
        },
        writable: true,
        enumerable: false,
        configurable: true
      },
      'keyfor': {
        value: function(symbol) {
          for (var key in symbol_formap) {
            if (symbol_formap[key] === symbol) return key;
          }
          return undefined;
        },
        writable: false,
        enumerable: false,
        configurable: true  //若为false，报错Uncaught TypeError: Cannot redefine property
      }
    });
    return symbol;
  }

  root.SymbolPolyfill=SymbolPolyfill;
})();

let symbol1=SymbolPolyfill();
console.log(symbol1);
console.log(symbol1.toString());
let symbol2=SymbolPolyfill();
console.log(symbol2);
// let symbol3=new SymbolPolyfill();

module.exports=symbol1;
